import React from "react";
import { DragSource } from "react-dnd";
import utils from "../../../../../utils";
import ItemTypes from "../../content/view/ItemTypes";
import './index.less';
import { getDefaultData } from "../../component";

const spec = {
  beginDrag: props => {
    const { type, name } = props;
    const field = {
      type, name,
      uuid: utils.UUID(),
      config: getDefaultData(type)
    };

    return { field };
  },
  endDrag: (props, monitor) => {
    const droppedOut = monitor.getItem().field;
    
    if (monitor.didDrop()) return;
    
    props.onDragEnd(droppedOut, true);
  }
};
const collect = connect => ({
  connectDragSource: connect.dragSource()
});

class FormField extends React.Component {
  render() {
    const { connectDragSource, type, name, onClick } = this.props;
    const clsName = type.toLowerCase();
    const FieldItem = (
      <div className='edc-form-field' onClick={onClick}>
        <i className={`icon-edc-f-${clsName}`}></i>
        <span className='wea-f12'>{name}</span>
      </div>
    );

    return connectDragSource(FieldItem);
  }
}

FormField.defaultProps = {
  onDragEnd: () => { },
  onClick: () => { }
};

export default DragSource(ItemTypes.FORMITEM, spec, collect)(FormField);